﻿using System;
using System.IO;
using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Solution.Application.Extensions;
using Solution.Application.Injection;
using Solution.Application.Modules;
using Solution.Core.Dependency;
using StackExchange.Redis.Extensions.Core.Configuration;

namespace Solution.App
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            await CreateHostBuilder(args).Build().RunAsync();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(configureHost =>
        {
            configureHost.SetBasePath(Directory.GetCurrentDirectory());
        })
        .ConfigureAppConfiguration((configure) =>
        {
            configure.AddJsonFile("Configs/rabbit.json", true, true);
            configure.AddJsonFile("Configs/redis.json", true, true);
            configure.AddJsonFile("Configs/kafka.json", true, true);
        })
        .UseServiceProviderFactory(new AutofacServiceProviderFactory(container =>
        {
            container.AddJobs();
            container.AddAssembly(typeof(IHostedService), "Solution.Application");
            container.AddAssembly(typeof(ITransientDependency), "Solution.Core");
            container.AddAssembly(typeof(ITransientDependency), "Solution.Application");
            container.AddPipelineBehaviors();
        }))
        .ConfigureServices((hostContext, services) =>
        {
            services.AddOpenTracing();
            services.AddLogging(configure => configure.AddConsole());
            services.Configure<KafkaOptions>(hostContext.Configuration.GetSection("Kafka"));
            services.AddRedisMultiplexer(hostContext.Configuration.GetSection("Redis").Get<RedisConfiguration>());
            services.AddCAPRabbitMQ(hostContext.Configuration.GetSection("RabbitMQ").Get<RabbitMQOption>());
        })
        .ConfigureLogging(configure =>
        {
            configure.ClearProviders();
            configure.AddConsole();
            configure.SetMinimumLevel(LogLevel.Information);
            configure.AddNLog("Configs/nlog.config");
        });
    }
}